package yxy.game.pm2.module.godwar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import org.joda.time.DateTime;

import org.redisson.api.RMap;
import yxy.cherry.battle.Team;
import yxy.cherry.battle.module.Position;
import yxy.cherry.battle.module.record.result.BattleResult;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.godwar;
import yxy.cherry.data.bean.herodata;
import yxy.cherry.data.bean.map;
import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Format.FormatType;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.GodWarMessage;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.*;
import yxy.game.pm2.module.task.TaskHandle;

/** 战神殿 */
public class GodWarHandler {

	private String code() {
		return BattleType.GODWAR.name();
	}

	public Result battleResponseExecute(String playerCode, godwar data, int evolve, GodWarMessage.GodWarChanllengeExecuteResponse.Builder response)
			throws Exception {
		BattleHandle battleHandle = new BattleHandle();

		BattleModule battleModule = BattleModule.create(playerCode);
		battleModule.setType(BattleType.GODWAR);
		battleModule.setCode(code());

		GodWarAreaModule godwarModule = GodWarAreaModule.get(playerCode, data.getId());
		GodWarModule module = GodWarModule.get(playerCode);
		if (module.cooldown()) {
			int lesstime = (int) Math.abs(module.getCoolDownTime().getMillis() - DateTime.now().getMillis());
			return new Result(Result.GodWarCoolDown, lesstime);// 挑战冷却中
		}

		try {
			if (godwarModule.tryLock() && module.tryLock()) {
				int bossevolve = evolve + godwarModule.getEvolve();

				// 玩家的team
				TeamModule teamA = battleHandle.teamPlayer(playerCode, FormatType.普通);
				battleModule.setTeamA(teamA);

				// 玩家的team
				TeamModule teamB = teamGodWar(data, bossevolve);
				battleModule.setTeamB(teamB);

				Team team_a = teamA.team(true);
				Team team_b = teamB.team(false);
				team_a.setTeam对手(team_b);
				team_b.setTeam对手(team_a);

				// 处理战斗
				battleHandle.battleExecute(battleModule, team_a, team_b, 20);

				// 处理分数和奖励
				boolean isWin = battleModule.getBattleResult().equals(BattleResult.LEFT_WIN);

				// 冷却
				int cd = fomula.武魂殿挑战冷却时间分钟数.intValue();
				module.setCoolDownTime(DateTime.now().plusMinutes(cd));
				module.set();

				if (isWin) {
					Map<Integer, GodWarAreaModule> all = GodWarAreaModule.get(playerCode);
					for (GodWarAreaModule otherModule : all.values()) {
						if (otherModule.getDataId() == godwarModule.getDataId() || otherModule.getOccupantCode() == null) {
							continue;
						}
						if (otherModule.getOccupantCode().equals(playerCode)) {
							otherModule.recall();
							otherModule.set();
						}
					}

					godwarModule.setEvolve(bossevolve);
					godwarModule.occupy(playerCode);
					godwarModule.set();
				}

				// 处理录像
				if (isWin) {
					BattleRecord battleRecord = battleModule.saveRecord(BattleRecord.randomCode(), 1);

					GodWarRecord record = new GodWarRecord();
					record.setDataId(godwarModule.getDataId());

					record.setPlayerCode(playerCode);
					record.setNickName(teamA.getName());
					record.setPower(teamA.getPower());
					packFighter(record.getFighters(), teamA.getFighter_FU());
					packFighter(record.getFighters(), teamA.getFighter_FM());
					packFighter(record.getFighters(), teamA.getFighter_FD());
					packFighter(record.getFighters(), teamA.getFighter_BU());
					packFighter(record.getFighters(), teamA.getFighter_BM());
					packFighter(record.getFighters(), teamA.getFighter_BD());

					record.setDate(DateTime.now());
					record.setRecordCode(battleRecord.getCode());

					record.setEvolve(evolve);

					GodWarRecord.add(playerCode, record);

				}

				// 封装消息
				{
					BattleMessage.BattleExecuteResponse.Builder builder = BattleMessage.BattleExecuteResponse.newBuilder();
					builder.setPlayback(battleHandle.playback(battleModule));

					response.setBattleResp(builder);// 录像
					response.setBattleResult(battleModule.getBattleResult().getNumber());// 战果

					if (isWin) {
						response.addRewards(new CurrencyHandle().packItem(godwarModule.titleReward()));
					}
				}

				TaskHandle.handle(playerCode, TaskType.统计型_副本_武神殿_次数, 1);

				return Result.Success;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			godwarModule.unlock();
			module.unlock();
		}
		return Result.DataError;
	}

	private void packFighter(ArrayList<FighterModule> fighters, FighterModule fighter) {
		if (fighter == null) {
			return;
		}
		FighterModule result = new FighterModule();
		result.setHeroId(fighter.getHeroId());
		result.setLevel(fighter.getLevel());
		result.setStarlv(fighter.getStarlv());
		fighters.add(result);
	}

	public Result record(String playerCode, godwar data, GodWarMessage.GodWarRecordResponse.Builder response) {
		List<GodWarRecord> list = GodWarRecord.get(playerCode, data.getId());
		for (GodWarRecord record : list) {
			GodWarMessage.GodWarRecord.Builder builder = GodWarMessage.GodWarRecord.newBuilder();

			builder.setRecord(record.getRecordCode());
			builder.setDate(record.getDate().getMillis());
			builder.setEvolve(record.getEvolve());
			builder.setPlayerCode(record.getPlayerCode());
			builder.setNickname(record.getNickName());
			builder.setPower(record.getPower());
			for (FighterModule fighter : record.getFighters()) {
				HeroMessage.HeroSimple.Builder heroBuilder = HeroMessage.HeroSimple.newBuilder();
				heroBuilder.setCode("xxx");
				heroBuilder.setDataId(fighter.getHeroId());
				heroBuilder.setLevel(fighter.getLevel());
				heroBuilder.setStar(fighter.getStarlv());
				builder.addHeros(heroBuilder);
			}

			response.addRecords(builder);
		}

		return Result.Success;
	}

	public TeamModule teamGodWar(godwar data, int evolve) {
		TeamModule team = new TeamModule();
		// 武将
		for (int i = 0; i < data.getHeroid().length; i++) {
			Position position = Position.forValue(i + 1);
			int heroid = data.getHeroid()[i];
			int level = data.getGrade()[i] + evolve;
			int anger = data.getInitialangerup()[i];

			//如果找不到heroid默认不变  stage和star为0
			HashMap<String, Integer> map = BattleHandle.addStarAndStage(heroid, 0, 0, level);
			heroid = map.get("heroid");
			int stage = map.get("stage");
			int star = map.get("star");

			FighterModule fighterModule = FighterModule.create(heroid, level, stage, star, anger);
			fighterModule.setProperty(PropertyModule.create(BattleHandle.getOppositePropertyData(heroid, level, stage, star, anger)));

			team.addfighter(position, fighterModule);
		}
		// 神器
		WeaponModule weapon = WeaponModule.create(data.getWeapondataid(), data.getWeaponlv(), 0, 0, data.getWeaponskilllv());
		team.setWeapon(weapon);

		// 信息
		herodata _herodata = DataCenter.getData(data.getMain(), herodata.class);
		team.setName(_herodata.getName());
		team.setHead(data.getHeadid());
		team.setPower(team.power());

		return team;
	}

}
